iT邦幫忙

1

第40天~

Tzu 2021-08-19 20:53:241158 瀏覽
  • 分享至 

  • xImage
  •  

這個得上一篇:https://ithelp.ithome.com.tw/articles/10258374

看到數量再多按幾次會增加.再到cart-status.component.ts檔案:

https://ithelp.ithome.com.tw/upload/images/20210821/20119035TRo1V7J3Ff.png

然後也是updateCartStatus按右鍵修正:
https://ithelp.ithome.com.tw/upload/images/20210821/20119035vomBnhGIGq.png

再修改內容:

https://ithelp.ithome.com.tw/upload/images/20210821/20119035W0C0PCjO6F.png

import { CartService } from './../../services/cart.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-cart-status',
  templateUrl: './cart-status.component.html',
  styleUrls: ['./cart-status.component.css']
})
export class CartStatusComponent implements OnInit {

  totalPrice: number = 0.00;
  totalQuantity: number = 0;

  constructor(private CartService: CartService) { }

  ngOnInit(): void {
    this.updateCartStatus();
  }
  updateCartStatus() {

    this.CartService.totalPrice.subscribe(
      data => this.totalPrice = data

    );


  this.CartService.totalQuantity.subscribe(
    data => this.totalQuantity = data

  );


  }

}

然後再到cart-status.component.html檔案:修正{{ totalPrice | currency: 'USD'}}和 {{ totalQuantity}}

<div class="cart-area d-n">
  <a href="shopping-detail.html">
    <div class="total">{{ totalPrice | currency: 'USD'}}
      <span> {{ totalQuantity}}</span>
    </div>
     <i class="fa fa-shopping-cart"  aria-hidden="true"></i>
  </a>
</div>

最原本空的
https://ithelp.ithome.com.tw/upload/images/20210821/20119035cr0GEci35q.png
然後有新增的
https://ithelp.ithome.com.tw/upload/images/20210821/20119035Xj9EyKc2wG.png

  • 把購物車修到更好*

再來到cart.service.ts檔案:

找到這段CODE
https://ithelp.ithome.com.tw/upload/images/20210821/20119035IAp7B3gAwl.png

刪掉他再修正~tempCartItem => tempCartItem.id === tempCartItem.id持續測試到修正(3個等於)
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Equality_comparisons_and_sameness

嚴格相等(===)
嚴格相等比較兩個值,而被比較的兩個值都不會轉換成其他型別。如果值是不同型別,就會被視為不相等。如果兩值型別相同但不是數字,若值相同,則為相等。此外,如果兩個值皆為數字,只要他們是 NaN 以外的同一值,或者 +0 和 -0,則為相等。

import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CartService {

  CartItems: CartItem[]=[];

  totalPrice: Subject<number> = new Subject<number>();
  totalQuantity: Subject<number> = new Subject<number>();


  constructor() { }

  addToCart(theCartItem:CartItem){


    let alreadyExistsInCart : boolean = false;
    let existingCartItem: CartItem = undefined;

    if (this.CartItems.length>0){

     existingCartItem = this.CartItems.find( tempCartItem => tempCartItem.id === tempCartItem.id);

      alreadyExistsInCart =(existingCartItem != undefined);
    }

    if (alreadyExistsInCart){
      existingCartItem.quantity++;
    }
    else{
      this.CartItems.push(theCartItem);
    }

    this.computeCartTotals();


  }
  computeCartTotals() {

    let totalPriceValue: number =0;
    let totalQuantityValue: number =0;

    for(let currentCartItem of this.CartItems){
      totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
      totalQuantityValue += currentCartItem.quantity;
    }

    this.totalPrice.next(totalPriceValue);
    this.totalQuantity.next(totalQuantityValue);

    this.logCartData(totalPriceValue, totalQuantityValue);

      }
  logCartData(totalPriceValue: number, totalQuantityValue: number) {

    console.log('Contents of the cart');
    for (let tempCartItem of this.CartItems){
      const subTotalPrice = tempCartItem.quantity * tempCartItem.unitPrice;
      console.log(`name: ${tempCartItem.name}, quantity=${tempCartItem.quantity},unitPrice=${tempCartItem.unitPrice},subTotalPrice=${subTotalPrice}`);
    }

    console.log(`totalPrice: ${totalPriceValue.toFixed(2)}, totalQuantity: ${totalPriceValue}`);
    console.log('----');

  }
}

用chrome 開發者工具可以看到任點都OK

https://ithelp.ithome.com.tw/upload/images/20210822/20119035tHm2HYK1TV.png

讓產品細目裡的加入購物車的按鍵也有作用

到product-details.component.html檔案-從這句修改開始
https://ithelp.ithome.com.tw/upload/images/20210822/20119035X5s0JNKdnF.png

<div class="detail-section">

 <div class="container-fluid">

  <img src="{{product.imageUrl}}" class="detail-img">

  <h3>{{product.name}}</h3>

  <div class="price">{{product.unitPrice |currency:'USD'}}</div>
  <button (click)="addToCart()" class="btn btn-primary btn-sm" >Add to cart</button>

  <hr>
  <h4>Description</h4>
  <p>{{product.description}}</p>


  <a routerLink="/products" class="mt-5">Back to Product List</a>


 </div>
</div>

到這裡的addToCart會反紅
https://ithelp.ithome.com.tw/upload/images/20210822/20119035QDqW5YxgIW.png
是因為要去product-details.component.ts 檔案新增:

https://ithelp.ithome.com.tw/upload/images/20210822/20119035Kgu4uNur78.png

再到最下面:
https://ithelp.ithome.com.tw/upload/images/20210822/20119035lyNbAt6gRv.png

import { CartService } from './../../services/cart.service';
import { Routes, ActivatedRoute } from '@angular/router';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/common/product';
import { Component, OnInit } from '@angular/core';
import { CartItem } from 'src/app/common/cart-item';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {

  product:Product = new Product();

  constructor(private ProductService:ProductService,
              private CartService: CartService,
              private route:ActivatedRoute) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe(() =>{
      this.handleProductDetails();
    })
  }
  handleProductDetails() {
    const theProductId:number = +this.route.snapshot.paramMap.get('id');

    this.ProductService.getProduct(theProductId).subscribe(

      data =>{

        this.product = data;
      }
    )

      }

      addToCart(){
        console.log(`Adding to cart: ${this.product.name},${this.product.unitPrice}`);
        const theCartItem = new CartItem(this.product);
        this.CartService.addToCart(theCartItem);



      }



}

用chrome的開發者工具來檢查
https://ithelp.ithome.com.tw/upload/images/20210822/20119035EhstoQ1yap.png

這個得下一篇:https://ithelp.ithome.com.tw/articles/10258452


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言